package com.meida.module.bus.provider.api.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.meida.module.bus.client.entity.*;
import com.meida.module.bus.client.entity.srmapi.psmtosrm.PmsSrm01;
import com.meida.module.bus.client.entity.srmapi.psmtosrm.PmsSrm02;
import com.meida.module.bus.client.entity.srmapi.psmtosrm.PmsSrm02Detail;
import com.meida.module.bus.provider.api.util.ApiConstants;
import com.meida.module.bus.provider.api.util.PmsApiUtil;
import com.meida.module.bus.provider.api.util.PmsToolUtil;
import com.meida.module.bus.provider.mapper.BusMaterialComMapper;
import com.meida.module.bus.provider.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class PmsSrmApiSubService {
    @Autowired
    private BusMaterialSrmService srmService;
    @Autowired
    private BusMaterialSrmSubService srmSubService;
    @Autowired
    private BusMaterialService materialService;
    @Autowired
    private BusPurchaseService purchaseService;
    @Autowired
    private BusPurchaseDetailsService purchaseDetailsService;
    @Autowired
    private BusMaterialPlan100Service plan100Service;
    @Autowired
    private BusMaterialPlan200Service plan200Service;
    @Autowired
    private BusMaterialPackage100Service package100Service;
    @Autowired
    private BusMaterialPackage200Service package200Service;
    @Autowired
    private BusVersionService versionService;
    @Resource
    private BusMaterialComMapper busMaterialComMapper;
    @Autowired
    private PmsApiUtil pmsApiUtil;
    //-----------------------------------------PMS01处理--------------------------------------------------

    // 关闭部分或全部材料申请
    public void closePurchaseOrder(PmsSrm01 pmsSrm01) {
        List<BusPurchaseDetails> updDetail = Lists.newArrayList();
        pmsSrm01.getDetail().stream().forEach(detailReq -> {
            BusPurchaseDetails updObj = new BusPurchaseDetails();
            updObj.setPurchaseDetailsId(detailReq.getPurchaseDetailsId());
            updObj.setState(ApiConstants.STATE_99);
            updDetail.add(updObj);
        });
        purchaseDetailsService.updateBatchById(updDetail);

        // 如全部关闭，则关闭更新材料申请状态
        Map<String, Object> params = Maps.newHashMap();
        params.put(ApiConstants.MAP_PURCHASEID, pmsSrm01.getPurchaseId());
        List<BusPurchaseDetails> busPurchaseDetailsList = (List<BusPurchaseDetails>) purchaseDetailsService.listByMap(params);
        if (busPurchaseDetailsList.stream().allMatch(busPurchaseDetails -> busPurchaseDetails.getState() == ApiConstants.STATE_99)) {
            BusPurchase busPurchase = purchaseService.getById(pmsSrm01.getPurchaseId());
            busPurchase.setState(ApiConstants.STATE_99);
            purchaseService.updateById(busPurchase);
        }
    }

    // 关闭结果回写母表数据。
    public void backWriteMaterialBaseData(PmsSrm01 pmsSrm01) {
        BusPurchaseDetails header = purchaseDetailsService.getById(pmsSrm01.getDetail().get(0).getPurchaseDetailsId());
        Boolean verFlg = pmsApiUtil.getLastVer(header.getProjectId(), 1);
        pmsSrm01.getDetail().stream().forEach(detailSrmObj -> {
            BusPurchaseDetails busPurchaseDetailsObj = purchaseDetailsService.getById(detailSrmObj.getPurchaseDetailsId());
            if (verFlg) {
                // 更新100材料
                BusMaterialPlan100 busMaterialPlan100 = plan100Service.getById(busPurchaseDetailsObj.getMaterialId());
                backWriteMaterialBaseDataSub(busMaterialPlan100, busPurchaseDetailsObj.getOnLineNum(), busMaterialPlan100.getEndPurchaseCount(), busMaterialPlan100.getZtPurchaseCount());
                plan100Service.updateById(busMaterialPlan100);
            } else {
                // 更新200材料
                BusMaterialPlan200 busMaterialPlan200 = plan200Service.getById(busPurchaseDetailsObj.getMaterialId());
                backWriteMaterialBaseDataSub(busMaterialPlan200, busPurchaseDetailsObj.getOnLineNum(), busMaterialPlan200.getEndPurchaseCount(), busMaterialPlan200.getZtPurchaseCount());
                plan200Service.updateById(busMaterialPlan200);
            }

        });

        List<Long> purchaseOrderDetailIds = Lists.newArrayList();
        pmsSrm01.getDetail().stream().forEach(detailSrmObj -> {
            purchaseOrderDetailIds.add(detailSrmObj.getPurchaseDetailsId());
        });

        Map<String, Object> reqMap = Maps.newHashMap();
        reqMap.put(ApiConstants.MAP_PURCHASEID, pmsSrm01.getPurchaseId());
        List<BusMaterialReqMainData> busMaterialReqMainData = busMaterialComMapper.selectByMap(reqMap);
        List<BusMaterialReqMainData> busUpdData =
            busMaterialReqMainData.stream().filter(inPalnData -> purchaseOrderDetailIds.contains(inPalnData.getPurchaseDetailsId())).collect(Collectors.toList());

        if (ApiConstants.VER_100 == Integer.valueOf(busUpdData.stream().findFirst().get().getVer())) {
            // 更新100材料
            List<BusMaterialPlan100> busMaterialPlan100List = Lists.newArrayList();
            busUpdData.stream().forEach(updObj -> {
                BusMaterialPlan100 busMaterialPlan100 = plan100Service.getById(updObj.getMaterialId());
                backWriteMaterialBaseDataSub(busMaterialPlan100, updObj.getOnLineNum(), busMaterialPlan100.getEndPurchaseCount(), busMaterialPlan100.getZtPurchaseCount());
                busMaterialPlan100List.add(busMaterialPlan100);
            });
            plan100Service.updateBatchById(busMaterialPlan100List);
        } else {
            // 更新200材料
            List<BusMaterialPlan200> busMaterialPlan200List = Lists.newArrayList();
            busUpdData.stream().forEach(updObj -> {
                BusMaterialPlan200 busMaterialPlan200 = plan200Service.getById(updObj.getMaterialId());
                backWriteMaterialBaseDataSub(busMaterialPlan200, updObj.getOnLineNum(), busMaterialPlan200.getEndPurchaseCount(), busMaterialPlan200.getZtPurchaseCount());
                busMaterialPlan200List.add(busMaterialPlan200);
            });
            plan200Service.updateBatchById(busMaterialPlan200List);
        }
    }

    /**
     * 回写工程母表的材料计划剩余采购量&材料计划在途采购量
     *
     * @param planData         材料计划Obj
     * @param onLineNum        材料申请关闭明细中的在途数量
     * @param endPurchaseCount 材料计划剩余采购量
     * @param ztPurchaseCount  材料计划在途采购量
     */
    private void backWriteMaterialBaseDataSub(Object planData, BigDecimal onLineNum, BigDecimal endPurchaseCount, BigDecimal ztPurchaseCount) {
        // 材料计划剩余采购量 = 材料计划剩余采购量 + 材料申请关闭明细中的在途数量
        PmsToolUtil.setValue(planData, ApiConstants.INVOKE_SET_ENDPURCHASECOUNT, NumberUtil.add(endPurchaseCount, onLineNum));
        // 材料计划在途采购量 = 材料计划在途采购量 - 料申请关闭明细中的在途数量
        PmsToolUtil.setValue(planData, ApiConstants.INVOKE_SET_ZTPURCHASECOUNT, NumberUtil.add(ztPurchaseCount, onLineNum));
    }

    //-----------------------------------------PMS02处理--------------------------------------------------

    /**
     * SRM关联表更新对象设定
     *
     * @param detailReq detailReq
     * @param pmsSrm02  pmsSrm02
     * @return BusMaterialSrm
     */
    public BusMaterialSrm getSetBusMaterialSrmForPm02(PmsSrm02Detail detailReq, PmsSrm02 pmsSrm02) {
        BusMaterialSrm busMaterialSrm = new BusMaterialSrm();
        // PMS材料申请计划ID
        busMaterialSrm.setPurchaseId(detailReq.getPurchaseId());
        // PMS材料申请计划明细ID
        busMaterialSrm.setPurchaseDetailsId(detailReq.getPurchaseDetailsId());

        // 需求计划明细ID
        busMaterialSrm.setPlanId(detailReq.getPlanId());
        // 需求计划编码
        busMaterialSrm.setPlanNo(detailReq.getPlanNo());
        // 需求计划行号
        busMaterialSrm.setPlanRowno(detailReq.getRowNos());
        // 需求计划明细ID
        busMaterialSrm.setPlandtlId(detailReq.getPlanDtlId());

        // 采购申请ID
        busMaterialSrm.setPurchasingRequisitionId(pmsSrm02.getPurchasingRequisitionId());
        // 采购申请编码
        busMaterialSrm.setPurchasingRequisitionNo(pmsSrm02.getPurchasingRequisitionNo());
        // 采购申请明细ID
        busMaterialSrm.setPurchasingRequisitiondtlId(detailReq.getPurchasingRequisitionDtlId());
        // 采购申请明细行号
        busMaterialSrm.setPurchasingRequisitionRowno(detailReq.getRowNo());

        // 预留号
        busMaterialSrm.setReserveNo(detailReq.getReserveNo());
        // 预留行号
        busMaterialSrm.setReserveRow(detailReq.getReserveRow());


        return busMaterialSrm;
    }

    /**
     * 判断是否存在调拨
     * 存在调拨：更新材料申请的在途，到货，材料计划的在途，到货
     *
     * @param pmsSrm02
     */
    public void pms02Sub01(PmsSrm02 pmsSrm02) {
        Map<String, Object> searhMap = Maps.newHashMap();
        searhMap.put(ApiConstants.MAP_PURCHASEID, pmsSrm02.getDetail().get(0).getPurchaseId());
        // 获取材料申请详情全数据
        List<BusMaterialReqMainData> busMaterialReqMainDatas = busMaterialComMapper.selectByMap(searhMap);
        // 设定PMS材料申请相关信息
        List<BusPurchaseDetails> busPurchaseDetailsUpds = getUpdPurchaseDetails(pmsSrm02, busMaterialReqMainDatas);
        // 无调拨情况
        if (0 == busPurchaseDetailsUpds.size()) {
            return;
        }
        // 回写材料申请的到货数量，已采购量
        purchaseDetailsService.updateBatchById(busPurchaseDetailsUpds);

        // 回写材料计划表中的材料计划剩余采购量&材料计划在途采购量
        List<BusMaterialReqMainData> backMasterData =
            busMaterialReqMainDatas.stream().filter(
                masterData -> busPurchaseDetailsUpds.stream().anyMatch(
                    detail -> detail.getPurchaseDetailsId().equals(masterData.getPurchaseDetailsId()))).collect(Collectors.toList());

        List<BusMaterialPlan100> updPlan100s = Lists.newArrayList();
        List<BusMaterialPlan200> updPlan200s = Lists.newArrayList();
        Boolean verFlg = ApiConstants.VER_100 == Integer.valueOf(backMasterData.get(0).getVer());
        backMasterData.stream().forEach(backMasterObj -> {
            BusPurchaseDetails pmsDetail =
                busPurchaseDetailsUpds.stream().filter(detailObj -> detailObj.getPurchaseDetailsId().equals(backMasterObj.getPurchaseDetailsId())).findFirst().get();
            if (verFlg) {
                BusMaterialPlan100 plan100 = new BusMaterialPlan100();
                // 在途采购量 =  = 在途采购量 - PMS材料申请到货数量
                // 到货量 = 到货数量 + PMS材料申请
                updPlan100s.add((BusMaterialPlan100) setPurchaseOrderDetail2(plan100, backMasterObj.getMaterialId(),
                    backMasterObj.getOnLineNum(), backMasterObj.getReceiveNum(),
                    pmsDetail.getOnLineNum(), pmsDetail.getReceiveNum()
                ));
            } else {
                // 在途采购量 =  = 在途采购量 - PMS材料申请到货数量
                // 到货量 = 到货数量 + PMS材料申请
                BusMaterialPlan200 plan200 = new BusMaterialPlan200();
                updPlan200s.add((BusMaterialPlan200) setPurchaseOrderDetail2(plan200, backMasterObj.getMaterialId(),
                    backMasterObj.getOnLineNum(), backMasterObj.getReceiveNum(),
                    pmsDetail.getOnLineNum(), pmsDetail.getReceiveNum()
                ));
            }
        });
        plan100Service.updateBatchById(updPlan100s);
        plan200Service.updateBatchById(updPlan200s);

    }

    /**
     * 设定PMS材料申请相关信息
     *
     * @param pmsSrm02
     * @param busMaterialReqMainDatas
     * @return
     */
    private List<BusPurchaseDetails> getUpdPurchaseDetails(PmsSrm02 pmsSrm02, List<BusMaterialReqMainData> busMaterialReqMainDatas) {
        List<BusPurchaseDetails> busPurchaseDetailsUpds = Lists.newArrayList();
        // 全调拨: 采购申请单号/采购申请ID为空
        if (StrUtil.isEmpty(pmsSrm02.getPurchasingRequisitionNo())) {
            busMaterialReqMainDatas.stream().forEach(mainData -> {
                // 回写材料申请的在途数量 = ZERO
                // 回写材料申请的到货数量 = PMS采购申请数量 = SRM/SAP系统调拨量
                setPurchaseOrderDetail(busPurchaseDetailsUpds, mainData.getPurchaseDetailsId(), BigDecimal.ZERO, mainData.getPurchaseNum());
            });

        } else {
            List<Long> purchaseDetailsIds = Lists.newArrayList();
            pmsSrm02.getDetail().stream().forEach(detailObj -> {
                purchaseDetailsIds.add(detailObj.getPurchaseDetailsId());
            });

            // 部分调拨情景1：缺少的行,为调拨行
            List<BusMaterialReqMainData> notExsitsData =
                busMaterialReqMainDatas.stream().filter(masterData -> !purchaseDetailsIds.contains(masterData.getPurchaseDetailsId())).collect(Collectors.toList());
            notExsitsData.stream().forEach(dataObj -> {
                // 回写材料申请的在途数量 = ZERO
                // 回写材料申请的到货数量 = PMS采购申请数量 = SRM/SAP系统调拨量
                setPurchaseOrderDetail(busPurchaseDetailsUpds, dataObj.getPurchaseDetailsId(), BigDecimal.ZERO, dataObj.getPurchaseNum());
            });

            // 部分调拨情景2：已存在的行，SRM采购申请的数量 < PMS材料申请的数量，存在调拨数量的
            List<BusMaterialReqMainData> exsitsData =
                busMaterialReqMainDatas.stream().filter(masterData -> !purchaseDetailsIds.contains(masterData.getPurchaseDetailsId())).collect(Collectors.toList());
            List<PmsSrm02Detail> srmDetailUpds = Lists.newArrayList();
            exsitsData.stream().forEach(masterData -> {
                List<PmsSrm02Detail> detail =
                    pmsSrm02.getDetail().stream().filter(
                        srmInfo ->
                            !masterData.getPurchaseNum().equals(srmInfo.getQuantityDemanded())).collect(Collectors.toList());
                if (0 < detail.size()) {
                    srmDetailUpds.add(detail.get(0));
                }
            });
            srmDetailUpds.stream().forEach(srmDe -> {
                // 回写材料申请的在途数量: SRM材料申请数量
                // 回写材料申请的到货数量：PMS材料申请数量 - SRM材料申请数量
                BusMaterialReqMainData findData =
                    exsitsData.stream().filter(exsitsDataObj -> exsitsDataObj.getPurchaseDetailsId().equals(srmDe.getPurchaseDetailsId())).findFirst().get();
                setPurchaseOrderDetail(busPurchaseDetailsUpds, srmDe.getPurchaseDetailsId(),
                    srmDe.getQuantityDemanded(),
                    NumberUtil.sub(findData.getPurchaseNum(), srmDe.getQuantityDemanded()));
            });
        }
        return busPurchaseDetailsUpds;
    }

    /**
     * 设定采购申请回写对象
     *
     * @param busPurchaseDetailsUpds 对象集合
     * @param detailId               明细ID
     * @param onLineNum              在途数量
     * @param receiveNum             到货数量
     */
    private void setPurchaseOrderDetail(List<BusPurchaseDetails> busPurchaseDetailsUpds, Long detailId, BigDecimal onLineNum, BigDecimal receiveNum) {
        BusPurchaseDetails purchaseDetailUpd = new BusPurchaseDetails();
        purchaseDetailUpd.setPurchaseDetailsId(detailId);
        // 回写材料申请的在途数量
        purchaseDetailUpd.setOnLineNum(onLineNum);
        // 回写材料申请的到货数量
        purchaseDetailUpd.setReceiveNum(receiveNum);
        busPurchaseDetailsUpds.add(purchaseDetailUpd);
    }

    private Object setPurchaseOrderDetail2(Object planData,
                                           Long materialPlanId,
                                           BigDecimal onLineNumFromPlan100,
                                           BigDecimal receiveNumFromPlan100,
                                           BigDecimal onLineNumFromDetail,
                                           BigDecimal receiveNumFromDatil) {

        PmsToolUtil.setValue(planData, "setMaterialId", materialPlanId);
        // 在途采购量 = 在途采购量 - PMS材料申请到货数量
        PmsToolUtil.setValue(planData, "setZtPurchaseCount", NumberUtil.sub(onLineNumFromPlan100, onLineNumFromDetail));
        // 到货量 = 到货数量 + PMS材料申请
        PmsToolUtil.setValue(planData, "setDhPurchaseCount", NumberUtil.add(receiveNumFromPlan100, receiveNumFromDatil));
        return planData;
    }

//    /**
//     * SRM关联表更新
//     * 场景0-> PMS02: SAP平衡利库—>SRM接收->PMS接收【只更新关联主表】
//     * 场景1-> PMS03: SRM开口合同->PMS接收【关联主表无操作，子表会有新建】
//     * 场景2-> PMS04: SRM供应商点确认—>SRM接收->PMS接收【第一次发送时：关联表会无操作，子表会有新建】合同变更时，会出现更新
//     *
//     * @param busMaterialSrms busMaterialSrms
//     */
//    public void saveOrUpDateBusMaterialSrm(List<BusMaterialSrm> busMaterialSrms, int kind) {
//        // 场景0-> PMS02: SAP平衡利库—>SRM接收->PMS接收【只更新关联主表】
//        if (ApiConstants.BUSMATERIALSRM_ZERO == kind) {
//            // SAP平衡利库—>SRM接收->PMS接收
//            // 插入需求计划，采购申请
//            srmService.saveBatch(busMaterialSrms);
//
//        } else {
//            List<BusMaterialSrmSub> saveBusMaterialSrmSub = Lists.newArrayList();
//            busMaterialSrms.stream().forEach(busMaterialSrm -> {
//                Map<String, Object> param = Maps.newHashMap();
//                param.put(ApiConstants.MAP_PURCHASEID, busMaterialSrm.getPurchaseId());
//                param.put(ApiConstants.MAP_PURCHASEDETAILSID, busMaterialSrm.getPurchaseDetailsId());
//                Collection<BusMaterialSrm> busMaterialSrmsColl = srmService.listByMap(param);
//                if (0 < busMaterialSrmsColl.size()) {
//                    Long busMaterialSrmId = busMaterialSrmsColl.stream().findFirst().get().getBusMaterialSrmId();
//                    // 合同，订单信息不为空时
//                    if (0 < busMaterialSrm.getBusMaterialSrmSubList().size()) {
//                        BusMaterialSrmSub busMaterialSrmSub = new BusMaterialSrmSub();
//                        busMaterialSrmSub.setBusMaterialSrmId(busMaterialSrmId);
//                        BeanUtil.copyProperties(busMaterialSrm.getBusMaterialSrmSubList().get(0), busMaterialSrmSub);
//                        saveBusMaterialSrmSub.add(busMaterialSrmSub);
//                    }
//                    if (0 < busMaterialSrm.getBusDeliverSrms().size()) {
//                        BusDeliverSrm busDeliverSrm = new BusDeliverSrm();
//                    }
//
//
//                    // 场景2-> PMS04: SRM供应商点确认—>SRM接收->PMS接收【第一次发送时：关联表会无操作，子表会有新建】合同变更时，会出现更新
//
////                    if (ApiConstants.BUSMATERIALSRM_ONE == kind
////                        || ApiConstants.BUSMATERIALSRM_TWO == kind) {
////
////                    }
//                }
//            });
//            // 子表：合同采购订单关联表更新
//            if (0 < saveBusMaterialSrmSub.size()) {
//                srmSubService.saveBatch(saveBusMaterialSrmSub);
//            }
//        }
//
//    }


//    /**
//     * 获取最新分包计划Object
//     *
//     * @param ver                版本
//     * @param materialPackageIds
//     * @return
//     */
//    public Map<String, Object> getMaterialPackage(Integer ver, Long materialPackageIds) {
//        Map<String, Object> rsMap = Maps.newHashMap();
//        if (ApiConstants.VER_100 == ver) {
//            BusMaterialPackage100 busMaterialPackage100 = package100Service.getById(materialPackageIds);
//            rsMap.put(ApiConstants.MAP_VER, ver);
//            rsMap.put(ApiConstants.MAP_BUSMATERIALPACKAGE, busMaterialPackage100);
//
//        } else {
//            BusMaterialPackage200 busMaterialPackage200 = package200Service.getById(materialPackageIds);
//            rsMap.put(ApiConstants.MAP_VER, ver);
//            rsMap.put(ApiConstants.MAP_BUSMATERIALPACKAGE, busMaterialPackage200);
//        }
//        return rsMap;
//    }

    public void setSrmPackageId(Object packageObj, BusProjectSupplier busProjectSupplier, Long busMaterialSrmSubId, Long vendorIdIn) {
        for (int i = 1; i < ApiConstants.INT_ELEVEN; i++) {
            Long vendorId = PmsToolUtil.getLongValue(busProjectSupplier, ApiConstants.INVOKE_GET_SUPPLIERID + i);
            if (null != vendorId & vendorId.equals(vendorIdIn)) {
                if (null != PmsToolUtil.getValue(packageObj, ApiConstants.INVOKE_GET_SUPPLIERNUM + i)) {
                    PmsToolUtil.setValue(packageObj, ApiConstants.INVOKE_SET_SRMPACKAGEID + i, busMaterialSrmSubId);
                    break;
                }
            }
        }

    }

}


